<?php

namespace app\api\controller;

use app\admin\model\vppz\FamilyMembers;
use app\common\controller\Api;
use app\common\library\token\driver\Redis;
use \app\admin\model\vppz\ExaminationOrder as ExaminationOrderModel;
use Cassandra\Uuid;

/**
 * 示例接口
 */
class Crontab extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['madecalPlan', 'delmadecalPlan','cancelVip','createUser','cancelVipOrder','msQueue','sendMsg','tijianNotice'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['madecalPlan','tijianNotice'];
    protected $object = '';
    //体检通知
    public function tijianNotice(){
        $crontabModel = new ExaminationOrderModel();
        $data = $crontabModel->where([
            'has_send_notice' => 0,
            'exam_date'=>date('Y-m-d',time()+86400)
        ])->order('createtime','desc')->select();
        if(empty($data) === FALSE){
            foreach ($data as &$v){
                //todo 发通知
                // 配置参数
                $AppModel = new \app\admin\model\vppz\App();
                $app = $AppModel->find(1);
                $appid = $app['wxapp_id'];
                $secret = $app['wxapp_secret'];
                if (empty($this->object)) {
                    $this->object = new \Wxchat($appid, $secret);
                }
                $accessToken = $this->object->getaccesstoken();
                if (empty($v['openid']) === FALSE) {
                        $send_data = array(
                            "thing1" => array(
                                "value" => $v['exam_person_name']
                            ),
                            "time2" => array(
                                "value" => $v['exam_date']
                            ),
                            "thing3" => array(
                                "value" => $v['hospital_address']??'联系客服'
                            ),
                            "thing4" => array(
                                "value" => '请按预约时间准时进行体检'
                            ),
                            "character_string5" => array(
                                "value" => $v['exam_time_slot']
                            ),
                        );
                        \Wxchat::sendtmpldetail($v['openid'], 'DOBvMP_u1QabSRLSp-oPfqyCF1afM6Wfb3xuNUBYWuQ', $accessToken, $send_data);
                    }
                $crontabModel->where('id',$v['id'])->where([
                    'has_send_notice' => 1,
                    'updatetime'=>time()
                ]);
            }
        }
        $this->success('返回成功', $this->request->param());
    }
    //推送用药计划
    public function madecalPlan()
    {
        $crontabModel = new \app\admin\model\Crontab();
        $data = $crontabModel->where([
            'type' => 1
        ])->where('next_time','<',time())->select();
        $panModel = new \app\admin\model\vppz\MedicationPlan();
        if(empty($data) === FALSE){
            foreach ($data as &$v){
                //todo 发通知
                $plan = $panModel->where(['id'=>$v['plan_id']])->find();
                // 配置参数
                $AppModel = new \app\admin\model\vppz\App();
                $app = $AppModel->find(1);
                $appid = $app['wxapp_id'];
                $secret = $app['wxapp_secret'];
                if (empty($this->object)) {
                    $this->object = new \Wxchat($appid, $secret);
                }
                $accessToken = $this->object->getaccesstoken();
                $userModel = new \app\admin\model\vppz\User();
                $user = $userModel->where('id','=',$v['user_id'])->find();
                $guidances = array(
                    'before'=>'餐前',
                    'after'=>'餐后',
                    'empty'=>'空腹',
                    'with'=>'随餐服用 ',
                    'sleep'=>'睡前',
                );
                $familymodel = new \app\admin\model\vppz\FamilyMembers();
                $family = $familymodel->where([
                    'id'=>$v['family_id']
                ])->find();
                if($family['is_self'] == 1){
                    $family['relation'] = '本人';
                }
                $content = $plan['medication_name'].$plan['metering'].$plan['metering_unit'].'('.$plan['method'].','.$guidances[$plan['guidance']].')';
                if (empty($user) === FALSE) {
                    if (empty($user['openid']) === FALSE) {
                        $send_data = array(
                            "name1" => array(
                                "value" => $family['name'].'('.$family['relation'].')'
                            ),
                            "thing3" => array(
                                "value" => $content
                            ),
                            "time2" => array(
                                "value" => datetime($v['next_time'],'Y-m-d H:i')
                            )
                        );
                        \Wxchat::sendtmpldetail($user['openid'], '81eFQzi8bePe7EvMslK-J8BsLBL-it1dow6AlNOOf6E', $accessToken, $send_data);
                    }
                }
                $next_time = 0;
                if($plan['scheme'] == 0){
                    //每天几次
                    $times = json_decode($plan['time'],true);
                    sort($times);
                    foreach ($times as &$tv){
                        $tflag = strtotime(date('Y-m-d',time()).' '.$tv);
                        if($tflag > time() && $next_time == 0){
                            $next_time = strtotime(date('Y-m-d',time()).' '.$tv);
                        }
                    }
                    if($next_time == 0){
                        $next_time = strtotime(date('Y-m-d',time()).' '.$times[0]) + 86400;
                    }
                }elseif ($plan['scheme'] == 1){
                    //几天一次
                    $next_time = $v['next_time']+ $plan['num']*86400;
                }else{
                    //几小时一次
                   $next_time = $v['next_time']+ $plan['num']*3600;
                }
                $crontabModel->where('id','=',$v['id'])->update(array(
                    'next_time'=>$next_time,
                    'updatetime'=>time()
                ));
            }
        }
        $this->success('返回成功', $this->request->param());
    }
    //删除用药计划
    public function delmadecalPlan(){
        $crontabModel = new \app\admin\model\Crontab();
        $data = $crontabModel->where([
            'type' => 1
        ])->where('end_date','<',datetime(time(),'Y-m-d H:i:s'))->delete();
        $this->success('返回成功', $this->request->param());
    }
    //取消过期会员
    public function cancelVip(){
        $userModel = new \app\admin\model\vppz\User();
        $data = $userModel->where('expire_time','<',datetime(time(),'Y-m-d H:i:s'))
            ->where(['is_vip'=>1])->update(array(
            'is_vip'=>0,
            'updatetime'=>time()
        ));
        $this->success('返回成功', $this->request->param());
    }

    public function cancelVipOrder(){
        $userModel = new \app\admin\model\vppz\VipOrder();
        $data = $userModel->where('createtime','<',time()-1800)->where(['order_status'=>0])
            ->update(array(
            'order_status'=>4,
            'updatetime'=>time()
        ));
        $this->success('返回成功', $this->request->param());
    }
    //初始化模板消息队列
    public function msQueue(){
        $queue = new \app\admin\model\vppz\MsQueue();
        $lists = $queue->where(['status'=>0])->limit(0,1)->select();
        try {
            if(empty($lists)===FALSE){
                $redis = new Redis();
                $data = $lists[0];
                if($data['send_type'] == 'user'){
                    $user = \app\admin\model\vppz\User::where(['id'=>$data['user_id']])->field('id,nickname,openid')->find();
                    if(empty($user)===FALSE){
                        $name = $user->nickname;
                        $openid = $user->openid;
                        if(empty($name) ===FALSE && empty($openid) === FALSE) {
                            $content = json_decode($data['content'],true);
                            $senddata = array(
                                'openid'=>$openid,
                                'user_id'=>$user->id,
                                'nickname'=>$name,
                                'name'=>$name,
                                'address'=>$content['address'],
                                'username'=>$content['username']??'',
                                'keshi'=>$content['keshi']??'',
                                'hospital'=>$content['hospital']??'',
                                'date'=>$content['date']??'',
                                'content'=>$content['content'],
                                'type'=>$data['type']
                            );
                            $redis->lpush('msqueue',json_encode($senddata));

                        }
                    }

                }elseif($data['send_type'] == 'select'){
                    if (empty($data['user_id']) === FALSE){
                        foreach ($data['user_id'] as &$v){
                            $user = \app\admin\model\vppz\User::where(['id'=>$v])->field('id,nickname,openid')->find();
                            if(empty($user)===FALSE){
                                $name = $user->nickname;
                                $openid = $user->openid;
                                if(empty($name) ===FALSE && empty($openid) === FALSE) {
                                    $content = json_decode($data['content'],true);
                                    $senddata = array(
                                        'openid'=>$openid,
                                        'user_id'=>$user->id,
                                        'nickname'=>$name,
                                        'name'=>$name,
                                        'address'=>$content['address'],
                                        'username'=>$content['username']??'',
                                        'keshi'=>$content['keshi']??'',
                                        'hospital'=>$content['hospital']??'',
                                        'date'=>$content['date']??'',
                                        'content'=>$content['content'],
                                        'type'=>$data['type']
                                    );
                                    $redis->lpush('msqueue',json_encode($senddata));

                                }
                            }
                        }
                    }
                }else{
                    $users = \app\admin\model\vppz\User::where(['is_vip'=>1])->select();
                    if (empty($users) === FALSE){
                        $content = json_decode($data['content'],true);
                        foreach ($users as &$v){
                            $senddata = array(
                                'openid'=>$v['openid'],
                                'nickname'=>$v['nickname'],
                                'user_id'=>$v['id'],
                                'name'=>$v['nickname'],
                                'address'=>$content['address'],
                                'username'=>$content['username']??'',
                                'keshi'=>$content['keshi']??'',
                                'hospital'=>$content['hospital']??'',
                                'date'=>$content['date']??'',
                                'content'=>$content['content'],
                                'type'=>$data['type']
                            );
                            $redis->lpush('msqueue',json_encode($senddata));
                        }
                    }
                }
                $queue->where(['id'=>$lists[0]['id']])->update(array(
                    'status'=>1,
                    'updatetime'=>time()
                ));
            }

            $this->success('返回成功', $this->request->param());
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            $this->error($e->getMessage());
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

    }
    //发送模板消息
    public function sendMsg(){
        set_time_limit(0);
        $redis = new Redis();
        for ($i=0;$i<100;$i++) {
            $data = $redis->rpop('msqueue');
            if (empty($data) === FALSE) {
                $resdata = json_decode($data, true);
                if ($resdata['type'] == 'yimiao') {
                    $res = \TempNotice::yimiaojiezhong($resdata['openid'],$resdata['name'],$resdata['address'],$resdata['content']);
                    $content1 = '尊敬的会员：'.$resdata['name'].'您好，'.$resdata['content'].',接种地点：'.$resdata['address'];
                    hook('send_message', [$resdata['user_id'], 'user', '疫苗通知', $content1]);
                } else if ($resdata['type'] == 'wenzhen'){
                    $content1 = '尊敬的会员：'.$resdata['name'].'您好，提醒内容：'.$resdata['content'].',提示说明：'.$resdata['address'];
                    hook('send_message', [$resdata['user_id'], 'user', '常规通知', $content1]);
                    $res = \TempNotice::wenzhentixing($resdata['address'],$resdata['content'],$resdata['openid']);
                }else if($resdata['type'] == 'jiuzhen'){
                    $senddata = array(
                        'openid'=>$resdata['openid'],
                        'name'=>$resdata['username'],
                        'keshi'=>$resdata['keshi'],
                        'hospital'=>$resdata['hospital'],
                        'date'=>$resdata['date'],
                        'content'=>$resdata['content']
                    );
                    $content1 = '尊敬的会员：'.$resdata['name'].'您好，就诊人：'.$resdata['username'].',就诊科室：'.$resdata['keshi'].',就诊医院：'.$resdata['hospital'].',就诊时间：'.$resdata['date'];
                    hook('send_message', [$resdata['user_id'], 'user', '就诊提醒', $content1]);
                    $res = \TempNotice::jiuzhentixing($senddata);
                }
            }
        }
        $this->success('返回成功', $this->request->param());
    }
    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    public function generateRandomPhoneNumber() {
        $prefixes = ['130', '131', '132', '133', '134', '135', '136', '137', '138', '139',
             '145', '147', '150', '151', '152', '153', '155', '156', '157', '158', '159',
             '165', '166', '167',
             '170', '171', '173', '175', '176', '177', '178',
             '180', '181', '182', '183', '184', '185', '186', '187', '188', '189',
             '198', '199'];

            // 随机选择一个前缀
            $prefix = $prefixes[array_rand($prefixes)];

            // 生成随机的9位数字（除去前缀的3位，总共是8位）
            $number = '';
            for ($i = 0; $i < 8; $i++) {
                $number .= mt_rand(0, 9);
            }

            // 组合成完整的手机号
            return $prefix . $number;
    }
    public function getname(){
        $surnames = ['王', '李', '张', '刘', '陈', '杨', '黄', '赵', '吴', '周',
        '徐', '孙', '马', '朱', '胡', '林', '郭', '何', '高', '罗',
        '郑', '梁', '谢', '宋', '唐', '许', '韩', '冯', '邓', '曹',
        '彭', '曾', '肖', '田', '董', '袁', '潘', '于', '蒋', '蔡',
        '余', '杜', '叶', '程', '苏', '魏', '吕', '丁', '任', '沈',
        '姚', '卢', '姜', '崔', '钟', '谭', '陆', '汪', '范', '金'];
        // 名字数组
        $names = ['伟', '刚', '勇', '毅', '俊', '峰', '强', '军', '平', '保',
        '东', '文', '辉', '力', '明', '永', '健', '世', '广', '志',
        '义', '兴', '良', '海', '山', '仁', '波', '宁', '贵', '福',
        '生', '龙', '建华', '建国', '建军', '志国', '志军', '卫东',
        '伟强', '俊杰', '志明', '志强', '晓东', '晓峰', '海涛', '海滨','秀', '娟', '英', '华', '慧', '巧', '美', '娜', '静', '淑',
        '惠', '珠', '翠', '雅', '芝', '玉', '萍', '红', '娥', '玲',
        '芬', '芳', '燕', '彩', '春', '菊', '兰', '凤', '洁', '梅',
        '琳', '敏', '梦', '佳', '欣', '莹', '琪', '琦', '妍', '嫣',
        '婷婷', '丽娜', '海燕', '晓燕', '美玲', '丽娟', '文静', '静怡',
        '雨欣', '雨桐', '思琪', '诗涵', '雅婷', '佳琪', '梦琪'];

        // 随机选择姓氏和名字
        $randomSurname = $surnames[array_rand($surnames)];
        $randomName = $names[array_rand($names)];

        // 组合生成完整的用户名称
        $username = $randomSurname . $randomName;
        return $username;
    }
    public function createUser()
    {
        $date = datetime(time(),'Y-m-d');
        $num = rand(20,50);
        for ($i=0;$i<$num;$i++){
            $is_vip = 0;
            if($i % 20 == 0){
                $is_vip = 1;
            }
            $name = $this->getname();
            $avatar = 'https://banyetang.oss-cn-beijing.aliyuncs.com/xiaochengxu/avatar.jpg';
            $data = array(
                'app_id'=>1,
                'area_id'=>rand(1,2),
                'nickname'=>$name,
                'avatar'=>$avatar,
                'mobile'=>$this->generateRandomPhoneNumber(),
                'openid'=>$this->generateRandomPhoneNumber(),
                'createtime'=>time()+rand(6,19)*3600,
                'updatetime'=>time()+rand(6,19)*3600,
                'type'=>1,
                'is_vip'=>$is_vip,
                'vip_level'=>0,
                'vip_time'=>time(),
                'expire_time'=>datetime(time()+180*86400,'Y-m-d H:i:s')
            );
            $ret = \app\admin\model\vppz\User::create($data);
            $id = $ret->getLastInsID();
            if($is_vip == 1){
                $age = rand(18,68);
                $birth = datetime(time()-$age*86400*365,'Y-m-d');
                $avator = 'https://banyetang.oss-cn-beijing.aliyuncs.com/xiaochengxu/avatar.jpg';
                $background = 'https://banyetang.oss-cn-beijing.aliyuncs.com/xiaochengxu/nancheng.jpeg';
                $familydata = array(
                    'user_id'=>$id,
                    'name'=>$name,
                    'relation'=>'本人',
                    'gender'=>rand(1,2),
                    'age'=>$age,
                    'birth'=>$birth,
                    'avator'=>$avator,
                    'background'=>$background,
                    'height'=>150,
                    'weight'=>65,
                    'health_tips'=>'健康生活每一天',
                    'blood_types'=>'A',
                    'is_self'=>1
                );
                FamilyMembers::create($familydata);
                $keytip = "bangyetang_qipao_info";

                $redis = new Redis();
                $redis->lpush($keytip,array(
                    'user'=>$name,
                    'action'=>'开通家庭医生会员'
                ));
            }
        }
        $this->success('返回成功', $this->request->param());
    }

    /**
     * 无需登录的接口
     *
     */
    public function test1()
    {
        $this->success('返回成功', ['action' => 'test1']);
    }

    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $this->success('返回成功', ['action' => 'test2']);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }

}
